<template>
  <div class="compare-container">
    <div class="chart-box-1 flex-between">
      <div class="chart-box">
        <div class="title">各班对比</div>
        <div ref="compareChart" class="chart"></div>
      </div>
      <div class="chart-box">
        <div class="title">成绩分布</div>
        <div ref="scoreChart" class="chart"></div>
      </div>
    </div>
    <div class="chart-box-2">
      <div class="title">题目列表</div>
      <div ref="questionChart" class="chart-box question-list-chart"></div>
      <!-- 题目列表 -->
      <div>题目列表：</div>
      <div class="question-index flex">
        <div
          class="index-item hover"
          v-for="(question, index) in questionList"
          :class="[index === curQuestionIndex && `index-item-active`]"
          :key="index"
          @click="onClickQuestionIndex(index)"
        >
          {{ question.showIndex }}
        </div>
      </div>
      <template v-if="curQuestionInfo">
        <AssignTopic
          :topic-data="TopicData"
          :index="questionList[curQuestionIndex].showIndex"
          :show-head="true"
        />
      </template>
    </div>
    <div class="chart-box-2">
      <div class="title">题目分析</div>
      <QuestionTable :task-id="props.taskId" />
    </div>
    <div class="chart-box-2">
      <div class="title flex-between">
        <span>知识点分析</span>
        <div class="tip-box flex">
          <div class="dot"></div>
          低于年级平均
        </div>
      </div>
      <AnalysisTable :task-id="props.taskId" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import {
  getClassComparison,
  getScoreDistribution,
  getQuestionCompareList,
  getQuestionList
} from '@/apis/assignment/index'
import QuestionTable from './QuestionTable.vue'
import AnalysisTable from './AnalysisTable.vue'
import AssignTopic from './AssignTopic.vue'
import { useEcharts } from '@/hooks'
import 'echarts/lib/component/dataZoom'
import 'echarts/lib/component/markLine'
import { cloneDeep } from 'lodash'

const props = defineProps({
  taskId: {
    required: true
  },
  classSelect: {
    required: true
  }
})

const compareChart = ref()
const compareOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    top: '10px',
    left: '2%',
    right: '4%',
    bottom: '10%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisTick: {
        alignWithLabel: true
      },
      nameTextStyle: {
        color: '#B1BDC2'
      },
      axisLabel: {
        textStyle: {
          color: '#B1BDC2' //坐标的字体颜色
        },
        interval: 0
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      max: 100,
      name: '正确（%）',
      nameTextStyle: {
        color: '#B1BDC2'
      },
      axisLabel: {
        textStyle: {
          color: '#B1BDC2' //坐标的字体颜色
        }
      }
    }
  ],
  series: [
    {
      name: '班级',
      type: 'bar',
      barWidth: '40px',
      color: '#7D8DEF',
      label: {
        show: true,
        position: 'top',
        color: '#B1BDC2'
      },
      nameTextStyle: {
        color: '#B1BDC2'
      },
      data: [],
      markLine: {
        symbol: ['none', 'none'], // 去掉箭头
        lineStyle: {
          color: '#7D8DEF',
          width: 2,
          type: 'solid'
        },
        label: {
          show: true,
          color: '#7D8DEF',
          position: 'insideEndTop',
          formatter: ({ value }) => {
            return '平均正确率：' + value
          }
        },
        data: [
          {
            type: 'average',
            yAxis: 0
          }
        ]
      }
    }
  ],
  dataZoom: []
})
/* eslint-enable */
const { compareInstance } = useEcharts(compareChart, compareOption)

const scoreChart = ref()
const scoreOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    top: '10px',
    left: '2%',
    right: '4%',
    bottom: '10%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      name: '正确率区间',
      data: [],
      nameLocation: 'middle',
      nameGap: 30,
      axisTick: {
        alignWithLabel: true
      },
      nameTextStyle: {
        color: '#B1BDC2'
      },
      axisLabel: {
        textStyle: {
          color: '#B1BDC2' //坐标的字体颜色
        },
        interval: 0
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      name: '人数 ',
      nameTextStyle: {
        color: '#B1BDC2'
      },
      axisLabel: {
        textStyle: {
          color: '#B1BDC2' //坐标的字体颜色
        }
      }
    }
  ],
  series: [
    {
      type: 'line',
      smooth: true,
      symbol: 'none',
      barWidth: '40px',
      color: '#7D8DEF',
      label: {
        show: true,
        position: 'top',
        color: '#B1BDC2'
      },

      lineStyle: {
        color: '#4BB4FF',
        dashOffset: 10,
        width: 5,
        shadowColor: '#4BB4FF',
        shadowBlur: 30,
        cap: 'round',
        shadowOffsetX: -6,
        // 设置阴影沿y轴偏移量为9
        shadowOffsetY: 20
      },
      nameTextStyle: {
        color: '#B1BDC2'
      },
      data: []
    }
  ],
  dataZoom: []
})
/* eslint-enable */
const { scoreInstance } = useEcharts(scoreChart, scoreOption)

const questionChart = ref()
const questionOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    top: '30px',
    left: '2%',
    right: '6%',
    bottom: '6%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisTick: {
        alignWithLabel: true
      },
      name: '题号'
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      max: 100,
      name: '正确率 / %'
    }
  ],
  series: [
    {
      name: '正确率',
      type: 'bar',
      barWidth: '40px',
      label: {
        show: true,
        position: 'top',
        color: '#000'
      },
      itemStyle: {
        color: ({ value }) => {
          let color = ''
          switch (true) {
            case value >= 80:
              color = '#25A780'
              break
            case value >= 60:
              color = '#ACDB4A'
              break
            default:
              color = '#DC4834'
          }
          return color
        }
      },
      data: []
    }
  ],
  dataZoom: []
})
/* eslint-enable */
const { questionInstance } = useEcharts(questionChart, questionOption)

// 题目列表
const questionList = ref([])
const curQuestionIndex = ref(0) // 大题索引
const curQuestionSubIndex = ref(-1) // 小题索引
const curQuestionInfo = ref(null) // 显示的题目

const TopicData = computed(() => {
  let res = cloneDeep(curQuestionInfo.value?.question_detail)
  if (curQuestionSubIndex.value !== -1) {
    res.subproblem = res.subproblem.splice(curQuestionSubIndex.value, 1)
  }
  return res
})

const onClickQuestionIndex = index => {
  curQuestionIndex.value = index

  // 选中子题目
  curQuestionSubIndex.value = -1
  let question = questionList.value[curQuestionIndex.value]

  if (question.parentId) {
    let parentQuestion = questionList.value.find(
      item => item?.question_id === question.parentId
    )
    curQuestionSubIndex.value = question.index
    curQuestionInfo.value = parentQuestion
  } else {
    curQuestionInfo.value = question
  }
}

// 查看任务下的题目
const getQuestionListInfo = async () => {
  let param = {
    task_id: props.taskId,
    class_id: props.classSelect.value,
    class_type: props.classSelect.class_type
  }
  const res = await getQuestionList(param)
  let list = (res.data || []).map((question, index) => {
    let resItem = {
      index,
      showIndex: index + 1,
      parentId: 0,
      status: 0,
      ...question
    }
    let list = []
    if (
      question.question_detail.subproblem &&
      question.question_detail.subproblem.length
    ) {
      list = question.question_detail.subproblem.map(
        (subQuestion, subIndex) => {
          let childQuestion = question.child_question[subIndex]
          return {
            index: subIndex,
            showIndex: index + 1 + '-' + (subIndex + 1),
            parentId: question.question_detail.id,
            status: 0,
            ...childQuestion,
            ...subQuestion
          }
        }
      )
    }
    return [resItem, ...list]
  })

  questionList.value = list.flat()
  if (questionList.value.length) {
    onClickQuestionIndex(0)
  }
}

/**
 * 各班对比
 */
const handleCompareChart = async () => {
  const res = await getClassComparison({
    task_id: props.taskId
  })

  const { class_avg_scores, overall_avg_score } = res.data
  compareOption.series[0].markLine.data[0].yAxis = (
    overall_avg_score * 100
  ).toFixed(0)

  compareOption.series[0].data = []
  compareOption.xAxis[0].data = []

  Object.keys(class_avg_scores).forEach(key => {
    compareOption.series[0].data.push((class_avg_scores[key] * 100).toFixed(0))
    compareOption.xAxis[0].data.push(key)
  })
}

/**
 * 正确率区间人数
 */
const handleScoreChart = async () => {
  const res = await getScoreDistribution({
    task_id: props.taskId
  })
  scoreOption.series[0].data = []
  scoreOption.xAxis[0].data = []
  res.data.forEach(item => {
    scoreOption.series[0].data.push(item.count)
    scoreOption.xAxis[0].data.push(item.range)
  })
}

/**
 * 各个题目平均正确率
 */
const handleQuestionChart = async () => {
  const res = await getQuestionCompareList({
    task_id: props.taskId
  })
  questionOption.series[0].data = []
  questionOption.xAxis[0].data = []
  res.data.forEach(item => {
    questionOption.series[0].data.push((item.average_accuracy * 100).toFixed(0))
    questionOption.xAxis[0].data.push(item.serial_number)
    if (item.child_average) {
      item.child_average.forEach(child => {
        questionOption.series[0].data.push(
          (child.average_accuracy * 100).toFixed(0)
        )
        questionOption.xAxis[0].data.push(
          item.serial_number + '-' + child.serial_number
        )
      })
    }
  })
  if (questionOption.series[0].data.length >= 20) {
    questionOption.dataZoom[0] = {
      type: 'slider',
      start: '0',
      end: '40',
      top: '90%',
      height: '6%',
      bottom: '6%',
      show: true
    }
    questionOption.grid.bottom = '12%'
  }
}
const initData = () => {
  handleCompareChart()
  handleScoreChart()
  handleQuestionChart()
  getQuestionListInfo()
}

initData()
</script>

<style lang="less" scoped>
.compare-container {
  margin-bottom: 30px;
  .title {
    margin-bottom: 20px;
    font-size: bold;
    .tip-box {
      gap: 10px;
      .dot {
        width: 5px;
        height: 5px;
        border-radius: 100%;
        background-color: #ea4338;
      }
    }
  }
  .chart-box-1 {
    .chart-box {
      padding: 20px;

      background: #fff;
      .chart {
        width: 760px;
        height: 220px;
      }
    }
  }
  .chart-box-2 {
    padding: 20px;
    background: #fff;
    margin-top: 20px;
    .question-list-chart {
      margin-top: 40px;
      height: 360px;
      width: calc(100vw - 300px);
    }
    .question-index {
      flex-wrap: wrap;
      margin-bottom: 10px;
      gap: 16px;

      .index-item {
        min-width: 24px;
        height: 24px;
        border-radius: 5px;
        border: 1px solid black;
        text-align: center;
        line-height: 24px;
        display: inline-block;
        padding: 0 4px;
        color: #5466e7;
        border-color: #5466e7;

        &:hover {
          background-color: #e9eeff;
          border-color: #e9eeff;
        }
      }

      .index-item-active {
        height: 30px;
        min-width: 24px;
        margin-top: 2px;
        border: unset;
        color: #fff;
        background: url('@/assets/images/assignment/index-0-active.png')
          no-repeat;
        background-size: 100% 100%;
      }
    }
  }
}
</style>
